package com.stud.framework.web.service;

import javax.annotation.Resource;

import com.stud.common.constant.UserConstants;
import com.stud.common.core.domain.model.LoginBody;
import com.stud.common.exception.user.UserException;
import com.stud.common.utils.*;
import com.stud.system.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import com.stud.common.constant.CacheConstants;
import com.stud.common.constant.Constants;
import com.stud.common.core.domain.entity.SysUser;
import com.stud.common.core.domain.model.LoginUser;
import com.stud.common.core.redis.RedisCache;
import com.stud.common.exception.ServiceException;
import com.stud.common.exception.user.UserPasswordNotMatchException;
import com.stud.common.utils.ip.IpUtils;
import com.stud.framework.manager.AsyncManager;
import com.stud.framework.manager.factory.AsyncFactory;
import com.stud.framework.security.context.AuthenticationContextHolder;
import com.stud.system.service.SysConfigService;
import com.stud.system.service.SysUserService;

/**
 * 登录校验方法
 *
 * @author Stud
 */
@Component
@Slf4j
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录验证
     *
     * @param loginBody
     * @return 结果
     */
    public String login(LoginBody loginBody, String userType, int clientType) {
        // 用户验证
        Authentication authentication;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用 UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        loginUser.setIsApp(loginBody.getIsApp());
        if (!StringUtils.equals(loginUser.getUserType(), userType)) {
            throw new UserException("user.usertype.error");
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUserId());
        loginUser.setIp(loginBody.getIp());

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * sso登录验证
     *
     * @param loginBody
     * @return 结果
     */
    public String sso(LoginBody loginBody) {
        return login(loginBody, UserConstants.USER_TYPE_SSO, Constants.LOGIN);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String validateCaptcha(String username, String code, String uuid) {

        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (!captchaEnabled) {
            return null;
        }

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            return MessageUtils.message("user.jcaptcha.expire");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            return MessageUtils.message("user.jcaptcha.error");
        }
        return null;
    }


    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public boolean validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) {
            throw new ServiceException("验证码已失效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码错误");
        }
        return true;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

}
